<?php
namespace app\admin\controller\system;

use app\common\controller\AdminController;
use think\App;
use think\facade\Session;
use think\facade\View;
/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="管理员管理")
 */
class Admin extends AdminController
{

    protected $sort = [
        'sort' => 'desc',
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = app('app\common\model\system\SystemAdmin');
        $this->auth = app('app\common\model\system\SystemAuth');
        $this->store = app('app\common\model\mall\Store');
    }
    public function get_with(){
        return 'Store';
    }

    /**
     * 查询所属商家账号下信息
     */
    public function get_where($arr = []){

            //$array['store_id'] = $this->model->get_store();
        $this->model->get_store() && $array[] = ['store_id','=',$this->model->get_store()];
            //$array['app_id'] = $this->model->getApp();
            $array[] = ['app_id','=',$this->model->getApp()];
        $array[] = ['id','<>',11];
        if(isset($arr['phone']) && !empty($arr['phone'])){
            $ids = $this->store->where('phone','=',$arr['phone'])->column('id');

          if(empty($ids)){
               $array[] = ['store_id','=','001'];
          }else{
              $array[] = ['store_id','in',$ids];
          }
            
        }

        if(isset($arr['username']) && !empty($arr['username'])){
            $array[] = ['username','like','%'.$arr['username'].'%'];
        }

        $array = array_filter($array);


        return $array;
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            try {
            $rule = [
                'username|登录账户'       => 'require|unique:system_admin,username,'.$post['id'].',id',
                'password|登录密码'       => 'require',
                'auth_ids|角色' => 'require',
            ];
            $this->validate($post, $rule);
            $post['store_id'] = $this->model->get_store();
            $post['app_id'] = $this->model->getApp();
            $post['password'] = password($post['password']);
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * 获取附带数据
     * @param Request $request
     * @return mixed
     */
    public function otherData($request)
    {
        $user =  Session::get('admin');

        $otherData = $this->auth->where(['app_id'=>$this->model->getApp(),'store_id'=>$user['store_id']])->select();

        View::assign('otherData',$otherData);
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $id = $this->request->param('id');
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()){
            try {
            $post = $this->request->post();
            $rule = [
                'username|登录账户'      => 'require|unique:system_admin,username,'.$post['id'].',id',
                'password|登录密码'      => 'require',
                'auth_ids|角色'         => 'require',
            ];
            $this->validate($post, $rule);
                if($row['password']!==$post['password']){
                    $data['password'] = password($post['password']);
                }
                $data['auth_ids'] = $post['auth_ids'];
                $data['username'] = $post['username'];

                $save = $row->save($data);
            } catch (\Exception $e) {
                $this->error('保存失败'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row->auth_ids = explode(',', $row->auth_ids);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        empty($row) && $this->error('数据不存在');
        $id == 1 && $this->error('超级管理员不允许修改');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFileds)){
            $this->error('该字段不允许修改：' . $post['field']);
        }
        if ($post['id'] == AdminConstant::SUPER_ADMIN_ID && $post['field'] == 'status'){
            $this->error('超级管理员状态不允许修改');
        }
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }
    //修改客服状态
    public function action(){

        $param= $this->request->param();

        try{
            $row = $this->model->where('id',$param['id'])->find();
            $row->save($param);

        }catch (\Exception $exception){
            return json(['code'=>1,'msg'=>$exception->getMessage()]);
        }
        return json(['code'=>0,'msg'=>'操作成功']);
    }
}